import json
from pkgutil import get_data
import re
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from boke import settings
from users import models
from utils.mydecorators import check_login
from django.contrib.auth.hashers import make_password, check_password
from django.views import View
from django_redis import get_redis_connection
from users.models import Article,Tag, User
from utils.myjwt import generate_token
from utils.send_sms_code import send_message
from qiniu import Auth,put_data

# Create your views here.

class Register(View):
    def post(self, request):
        data = json.loads(request.body.decode())
        phone = data.get('phone')
        username = data.get('username')
        password = data.get('password')
        
        if not phone:
            return JsonResponse({'msg': '手机号不能为空', 'status': 400}, safe=False)
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return JsonResponse({'msg': '手机号格式不正确', 'status': 400}, safe=False)
        
        # 修复：让 make_password 自动生成 salt
        if password:
            hashed_pwd = make_password(password)
        
        try:
            user = User.objects.create(username=username, password=hashed_pwd, phone=phone)
            return JsonResponse({'msg': '注册成功', 'status': 200}, safe=False)
        except Exception as e:
            return JsonResponse({'msg': f'注册失败，原因是{e}', 'status': 400}, safe=False)
        
class PwdLogin(View):
    def post(self, request):
        """账号密码登录"""
        data = json.loads(request.body.decode())
        username = data.get('username')
        print("<<<<<<<username>>>>>>>>>", username)
        password = data.get('password')
        print("<<<<<<password>>>>", password)
        if not all([username, password]):
            return JsonResponse({'msg': '账号密码不能为空', 'status': 400}, safe=False)
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            return JsonResponse({'msg':'用户尚未注册','code':400},safe=False)
        
        if check_password(password,user.password):
            token = generate_token(user)
            return JsonResponse({'msg':'登录成功','code':200,'token':f'Bearer {token}'},safe=False)
        else:
            return JsonResponse({'msg':'密码不正确','code':400},safe=False)

    @method_decorator(check_login) 
    def put(self, request):
        """修改密码"""
        data = json.loads(request.body.decode())
        username = request.user
        print("<<<<<username>>>>",username)
        new_password = data.get('new_password')
        second_password = data.get('second_password')
        if new_password != second_password:
            return JsonResponse({'msg':'第二次输入密码和第一次输入密码不匹配','code':400},safe=False)
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            return JsonResponse({'msg':'用户尚未注册','code':400},safe=False)
        hashed_pwd = make_password(new_password,salt=settings.SECRET_KEY)
        try:
            user.password = hashed_pwd
            user.save()
            return JsonResponse({'msg':'密码修改成功','code':201},safe=False)
        except Exception as e:
            return JsonResponse({'msg':f'密码修改失败，原因是{e}','code':400},safe=False)

class Sendcode(View):
    def post(self, request):
        """发送短信验证码"""
        data = json.loads(request.body.decode())
        phone = data.get('phone')
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return JsonResponse({'msg': '手机号格式不正确', 'status': 400}, safe=False)
        # 发送短信验证码
        rest = send_message(phone)

        if json.loads(rest)['statusCode'] == '000000':
            return JsonResponse({'msg': '短信验证码发送成功', 'status': 200}, safe=False)
        else:
            JsonResponse({'msg': '短信验证码发送失败', 'status': 200})


class CodeLogin(View):
    def post(self, request):
        """短信验证码登录"""
        data = json.loads(request.body.decode('utf-8'))
        phone = data.get('phone')
        code = data.get('code')
        client = get_redis_connection('sms_code')
        true_code = client.get(phone).decode('utf-8')
        if code == true_code:
            return JsonResponse({'code': 200, 'msg': '登录成功'}, safe=False)
        else:
            return JsonResponse({'code': 400, 'msg': '验证码错误'}, safe=False)
        
class UserInfo(View):
    def get(self,request):
        """获取个人信息"""
        users = [i.userinfo() for i in models.User.objects.all()]
        return JsonResponse({'msg':'用户信息获取成功','users':users,'code':200},safe=False)


class Category(View):
    def get(self, request):
        """获取所有的分类"""
        try:
            category_list = models.Category.objects.all()
            print(category_list)
            cate = [category.name for category in category_list]
            print(cate)
            data = {'cate_name': cate}
            print(data)
            return JsonResponse(data, status=200)
        except Exception as e:
            return JsonResponse({'message': f'获取数据失败: {str(e)}'}, status=500)
        
    def post(self, request):
        """添加分类"""
        data = json.loads(request.body.decode())
        name = data.get('name')
        if not name:
            return JsonResponse({'msg': '分类名称不能为空', 'code': 400}, safe=False)
        if models.Category.objects.filter(name=name).exists():
            return JsonResponse({'msg': '分类已存在', 'code': 400}, safe=False)
        try:
            category = models.Category.objects.create(name=name)
            return JsonResponse({'msg': '分类添加成功', 'code': 201}, safe=False)
        except Exception as e:
            return JsonResponse({'msg': f'分类添加失败，原因是：{e}', 'code': 400}, safe=False)   
    
    def put(self, request, category_id):
        """修改分类"""
        try:
            category = models.Category.objects.get(id=category_id)
        except models.Category.DoesNotExist:
            return JsonResponse({'msg': '分类不存在', 'code': 404}, safe=False)
        data = json.loads(request.body.decode())
        new_name = data.get('name')
        if not new_name:
            return JsonResponse({'msg': '分类名称不能为空', 'code': 400}, safe=False)
        # 检查新名称是否已被其他分类使用
        if models.Category.objects.filter(name=new_name).exclude(id=category_id).exists():
            return JsonResponse({'msg': '分类名称已存在', 'code': 400}, safe=False)  
        try:
            category.name = new_name
            category.save()
            return JsonResponse({'msg': '分类修改成功', 'code': 200}, safe=False)
        except Exception as e:
            return JsonResponse({'msg': f'分类修改失败，原因是：{e}', 'code': 400}, safe=False)


    def delete(self, request, category_id):
        """删除分类"""
        try:
            category = models.Category.objects.get(id=category_id)
        except models.Category.DoesNotExist:
            return JsonResponse({'msg': '分类不存在', 'code': 404}, safe=False)
        try:
            category.delete()
            return JsonResponse({'msg': '分类删除成功', 'code': 200}, safe=False)
        except Exception as e:
            return JsonResponse({'msg': f'分类删除失败，原因是：{e}', 'code': 400}, safe=False)
        

class Tag(View):
    def get(self,request):
        """获取所有标签"""
        try:
            tag_list = models.Tag.objects.all()
            tag = [tag.to_tag() for tag in tag_list]
            data = {'tags': tag}
            return JsonResponse(data, status=200)
        except Exception as e:
            return JsonResponse({'message': f'获取数据失败: {str(e)}'}, status=500)
    
    
    def post(self, request):
        """添加标签"""
        data = json.loads(request.body.decode())
        name = data.get('name')
        if not name:
            return JsonResponse({'msg': '标签不能为空', 'code':400}, safe=False)
        if models.Tag.objects.filter(name=name).exists():
            return JsonResponse({'msg':'标签已存在','code':400},safe=False)
        try:
            tag = models.Tag.objects.create(name=name)
            return JsonResponse({'msg':'标签添加成功','code':201},safe=False)
        except Exception as e:
            return JsonResponse({'msg':f'标签添加失败，原因是：{e}','code':400},safe=False)
        

class Article(View):
    def get(self, request):
        """获取所有文章"""
        articles = [article.to_article() for article in models.Article.objects.all()]
        print("<!!!!!!111", articles)
        return JsonResponse({'msg':'文章获取成功','code':200,'article_list':articles},safe=False)
    
    def post(self, request):
        """添加文章"""
        data = json.loads(request.body.decode())
        title = data.get('title')
        print('title',title)
        author = data.get('author')
        print('author', author)
        category_id = data.get('category')
        print('category_id',category_id)
        tag_name = data.get('name')
        print('tag_name',tag_name)
        text = data.get('text')
        print('text', text)
        cover_img = data.get('cover_img')
        print('cover_img', cover_img)

        if not all([title, author, text, cover_img]):
            return JsonResponse({'msg': '文章标题、作者、内容、封面图片不能为空', 'code': 400},safe=False)

        try:
            author_obj = models.Article.objects.get(author=author)
            print("<<<<<<<<<<>>>>",author_obj)
        except models.Article.DoesNotExist:
            return JsonResponse({'msg': '作者不存在','code': 400}, safe=False)
        
        # 分类处理
        category_obj = None  # 初始化为 None
        if category_id:  # 如果有传入分类ID
            try:
                category_obj = models.Category.objects.get(id=category_id)
            except models.Category.DoesNotExist:
                return JsonResponse({'msg': '分类不存在', 'code': 400}, safe=False)
        
        # 处理标签
        tag_objs = []
        for i in tag_name:
            tag, created = models.Tag.objects.get_or_create(name=tag_name)
            tag_objs.append(tag)
        
        try:
            # 创建文章对象
            article = models.Article.objects.create(
                title=title,
                author=author_obj,
                category=category_obj,
                text=text,
                cover_img=cover_img
            )
            # 添加标签
            article.tag.set(tag_objs)
            return JsonResponse({'msg': '文章添加成功', 'code': 201}, safe=False)
        except Exception as e:
            return JsonResponse({'msg': f'文章添加失败，原因是：{e}', 'code': 400}, safe=False)

# 获取文章详情
class GetArticleMess(View):
    def get(self, request, article_id):
        try:
            article = models.Article.objects.get(id=article_id)
            return JsonResponse({'msg': '文章详情获取成功','code': 200,'article': article.to_article()  # 调用模型的to_article方法
            })
        except models.Article.DoesNotExist:
            return JsonResponse({'message': '文章不存在'}, status=404)
        except Exception as e:
            return JsonResponse({'message': f'获取文章详情失败: {str(e)}'}, status=500)
        

# 上传头像
class Uoload(View):
    def post(self, request):
# 接受前端传来的图片
        file =request.FILES.get('file')
        print(">>>",file.name)#上传到七牛云
#需要填写你的 Access Key和 Secret Key
        access_key = 'JAo7YQ87r9La8fzS1SToxDdOaMywkKtn5CLDkzsl'
        secret_key = 'Wh5nGoBjH9aoIq2T72uymGeGjWrREzMB2YMxVPSG'
        q=Auth(access_key, secret_key)#要上传的空间
        bucket_name ='serein6'
        #上传后保存的文件名
        key = file.name
        #生成上传 Token，可以指定过期时间等
        token = q.upload_token(bucket_name, key, 3600)
        ret, info = put_data(token, key, file.read())
        print(ret, info)
        print(ret['hash'])
        if info.status_code == 200:
            # 上传成功，返回图片的外链url
            return JsonResponse({'url': 'http://sxd275n7b.hd-bkt.clouddn.com/' + key}, status=200)
        else:
            return JsonResponse({'error': '上传失败'}, status=500)
        



